import axios from 'axios'
import router from "@/router";

const request = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 5000
})

//response interceptor
//可以在接口响应后统一处理结果
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8'
    let honey_user = localStorage.getItem('honey-user');
    config.headers['token'] = honey_user ? JSON.parse(honey_user).token : '';
    return config
}, error => {
    console.error('request error' + error) // for debug
    return Promise.reject(error)
});

request.interceptors.response.use(
    response => {
        let res = response.data;

        //兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res;
        }
        if(res.code === '401'){
            router.push('/login')
        }
        return res;
    },
    error => {
        console.error('response error' + error)
        return Promise.reject(error)
    }
)

export default request